<template>
  <div class="todo-item" :class="todoItemClass">
    <div class="todo-content">
      <!-- 左侧：完成图标 -->
      <div class="todo-status-icon">
        <img v-if="todo.status === TodoStatus.COMPLETED" src="../../../assets/icon/finish.svg" alt="已完成" class="finish-icon" />
      </div>

      <!-- 中间：内容区域 -->
      <div class="todo-main" @click="handleItemClick" @dblclick="handleItemDblClick">
        <div class="todo-header">
          <!-- 置顶图标 -->
          <img v-if="todo.isTop" src="@/assets/icon/top.svg" alt="置顶" class="top-icon" />

          <!-- 标题 -->
          <h3 class="todo-title" :class="{ completed: todo.status === TodoStatus.COMPLETED }">
            <el-tag v-if="showCategoryName && todo.categoryName" size="small" :color="category?.color || '#909399'" class="category-name-tag" effect="light">
              {{ todo.categoryName }}
            </el-tag>
            {{ todo.title || '未命名待办事项' }}
          </h3>
          
          <div class="todo-meta">
            <!-- 状态标签 -->
            <el-tag
              :type="getStatusType(todo.status)"
              size="small"
              class="status-tag"
            >
              {{ getStatusLabel(todo.status) }}
            </el-tag>

            <!-- 分类标签 -->
            <el-tag
              v-if="category"
              :color="category.color"
              size="small"
              class="category-tag"
              effect="light"
            >
              {{ category.name }}
            </el-tag>
          </div>
        </div>

        <!-- 待办内容 -->
        <div v-if="todo.content" class="todo-description">
          <MarkdownRenderer :content="todo.content" theme="classic" />
        </div>

        <!-- 标签 -->
        <div v-if="todo.tags && todo.tags.length > 0" class="todo-tags">
          <el-tag
            v-for="tag in todo.tags"
            :key="tag"
            size="small"
            type="info"
            effect="plain"
          >
            {{ tag }}
          </el-tag>
        </div>

        <!-- 底部信息 -->
        <div class="todo-footer">
          <div class="todo-dates">
            <!-- 截止日期 -->
            <span v-if="todo.dueDate" class="due-date" :class="getDueDateClass()">
              <el-icon><Calendar /></el-icon>
              截止：{{ formatDate(todo.dueDate) }}
            </span>
            
            <!-- 创建时间 -->
            <span class="created-date">
              创建：{{ formatDate(todo.createdTime) }}
            </span>
            
            <!-- 完成时间 -->
            <span v-if="todo.completedAt" class="completed-date">
              完成：{{ formatDate(todo.completedAt) }}
            </span>
          </div>
        </div>
      </div>

      <!-- 右侧：操作按钮 -->
      <div class="todo-actions">
        <el-dropdown @command="handleAction">
          <el-button text :icon="More" />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="edit">
                <el-icon><Edit /></el-icon>
                编辑
              </el-dropdown-item>
              <el-dropdown-item
                command="complete"
                :disabled="todo.status === TodoStatus.COMPLETED || todo.status === TodoStatus.CANCELLED"
              >
                <el-icon><Check /></el-icon>
                完成
              </el-dropdown-item>
              <el-dropdown-item
                command="toggleStatus"
                :disabled="todo.status === TodoStatus.CANCELLED"
              >
                <el-icon><Check /></el-icon>
                {{ todo.status === TodoStatus.COMPLETED ? '标记未完成' : '标记完成' }}
              </el-dropdown-item>
              <el-dropdown-item
                command="setInProgress"
                v-if="todo.status === TodoStatus.TODO"
              >
                <el-icon><VideoPlay /></el-icon>
                开始处理
              </el-dropdown-item>
              <el-dropdown-item command="pin" divided>
                <el-icon><Top /></el-icon>
                {{ todo.isTop ? '取消置顶' : '置顶' }}
              </el-dropdown-item>
              <el-dropdown-item command="favorite">
                <el-icon><Star /></el-icon>
                {{ todo.isFavorite ? '取消收藏' : '收藏' }}
              </el-dropdown-item>
              <el-dropdown-item command="delete" divided>
                <el-icon><Delete /></el-icon>
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import {
  More, Edit, Delete, Check, Calendar, VideoPlay, Top, Star
} from '@element-plus/icons-vue'
import type { TodoItem, TodoCategory, UpdateTodoRequest } from '../types'
import { TodoStatus } from '../types'
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'

interface Props {
  todo: TodoItem
  category?: TodoCategory
  categories?: TodoCategory[]
  showCategoryName?: boolean
  selected?: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  update: [id: string, request: UpdateTodoRequest]
  delete: [id: string]
  toggle: [id: string]
  detail: [id: string]
  select: [id: string]
}>()


// 待办事项样式类
const todoItemClass = computed(() => {
  return {
    'is-completed': props.todo.status === TodoStatus.COMPLETED,
    'is-cancelled': props.todo.status === TodoStatus.CANCELLED,
    'is-overdue': isOverdue.value,
    'is-selected': props.selected
  }
})

// 是否逾期
const isOverdue = computed(() => {
  if (!props.todo.dueDate || props.todo.status === TodoStatus.COMPLETED) {
    return false
  }
  return new Date(props.todo.dueDate) < new Date()
})

// 获取状态类型
const getStatusType = (status: TodoStatus) => {
  const typeMap = {
    [TodoStatus.TODO]: 'info',
    [TodoStatus.IN_PROGRESS]: 'warning',
    [TodoStatus.COMPLETED]: 'success',
    [TodoStatus.CANCELLED]: 'danger'
  }
  return typeMap[status]
}

// 获取状态标签
const getStatusLabel = (status: TodoStatus) => {
  const labelMap = {
    [TodoStatus.TODO]: '待处理',
    [TodoStatus.IN_PROGRESS]: '进行中',
    [TodoStatus.COMPLETED]: '已完成',
    [TodoStatus.CANCELLED]: '已取消'
  }
  return labelMap[status]
}

// 获取截止日期样式类
const getDueDateClass = () => {
  if (!props.todo.dueDate) return ''
  
  const dueDate = new Date(props.todo.dueDate)
  const now = new Date()
  const diffDays = Math.ceil((dueDate.getTime() - now.getTime()) / (1000 * 3600 * 24))
  
  if (diffDays < 0) return 'overdue'
  if (diffDays <= 1) return 'urgent'
  if (diffDays <= 3) return 'warning'
  return ''
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 处理项目单击 - 选中
const handleItemClick = () => {
  emit('select', props.todo.id)
}

// 处理项目双击 - 跳转到详情页
const handleItemDblClick = () => {
  emit('detail', props.todo.id)
}

// 处理操作
const handleAction = async (command: string) => {
  switch (command) {
    case 'edit':
      emit('update', props.todo.id, props.todo)
      break
    case 'complete':
      emit('update', props.todo.id, { status: TodoStatus.COMPLETED })
      break
    case 'toggleStatus':
      emit('toggle', props.todo.id)
      break
    case 'setInProgress':
      emit('update', props.todo.id, { status: TodoStatus.IN_PROGRESS })
      break
    case 'pin':
      // 切换置顶状态
      emit('update', props.todo.id, { isTop: !props.todo.isTop })
      break
    case 'favorite':
      // 切换收藏状态
      emit('update', props.todo.id, { isFavorite: !props.todo.isFavorite })
      break
    case 'delete':
      try {
        await ElMessageBox.confirm(
          '确定要删除这个待办事项吗？',
          '确认删除',
          {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        emit('delete', props.todo.id)
      } catch {
        // 用户取消删除
      }
      break
  }
}

</script>

<style scoped>
.todo-item {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s ease;
}

.todo-item:hover {
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.todo-item.is-completed {
  opacity: 0.7;
  background: var(--el-bg-color-page);
}

.todo-item.is-cancelled {
  opacity: 0.5;
  background: var(--el-fill-color-light);
}

.todo-item.is-overdue {
  border-color: var(--el-color-danger);
}

.todo-item.is-selected {
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.todo-content {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.todo-status-icon {
  flex-shrink: 0;
  margin-top: 2px;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.finish-icon {
  width: 20px;
  height: 20px;
}

.todo-main {
  flex: 1;
  min-width: 0;
  cursor: pointer;
  padding: 4px;
  margin: -4px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.todo-main:hover {
  background-color: var(--el-fill-color-light);
}

.todo-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.todo-title {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  line-height: 1.4;
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
  display: flex;
  align-items: center;
  gap: 6px;
  justify-content: center;
}

.category-name-tag {
  flex-shrink: 0;
  color: #fff !important;
}

.todo-title.completed {
  text-decoration: line-through;
  color: var(--el-text-color-regular);
}

.todo-meta {
  display: flex;
  gap: 6px;
  flex-shrink: 0;
  align-items: center;
}

.top-icon {
  width: 16px;
  height: 16px;
  flex-shrink: 0;
  margin-right: 4px;
}

.priority-tag,
.status-tag,
.category-tag {
  margin: 0;
}

.todo-description {
  margin: 0 0 12px 0;
  color: var(--el-text-color-regular);
  font-size: 14px;
  line-height: 1.5;
}

.todo-description :deep(.markdown-content) {
  font-size: 14px;
  line-height: 1.5;
}

.todo-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  margin-bottom: 12px;
}

.todo-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.todo-dates {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.due-date,
.created-date,
.completed-date {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: var(--el-text-color-regular);
}

.due-date.overdue {
  color: var(--el-color-danger);
  font-weight: 500;
}

.due-date.urgent {
  color: var(--el-color-warning);
  font-weight: 500;
}

.due-date.warning {
  color: var(--el-color-warning);
}

.todo-actions {
  flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .todo-header {
    flex-wrap: wrap;
    gap: 6px;
  }
  
  .todo-title {
    font-size: 14px;
    order: 2;
    flex-basis: 100%;
  }
  
  .priority-tag {
    order: 1;
  }
  
  .todo-meta {
    order: 3;
    flex-wrap: wrap;
  }

  .todo-dates {
    flex-direction: column;
    gap: 4px;
  }
}

/* 深色模式适配 */
.dark .todo-item {
  background: #303030;
  border-color: #3a3a3a;
}

.dark .todo-item:hover {
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.dark .todo-item.is-completed {
  background: #282828;
}

.dark .todo-item.is-cancelled {
  background: #2a2a2a;
}

.dark .todo-item.is-selected {
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}
</style>